<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%@ taglib  prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<%@ taglib prefix="redis" uri="http://www.shopjsp.com/redisTag/functions" %>
<%@ taglib prefix="shiro" uri="http://shiro.apache.org/tags" %>
<c:set var="basePath" value="${redis:getSysConfig('base_path_back')}"/>
<c:set var="uploadPath" value="${redis:getSysConfig('uploadFileVisitRoot')}"/>
<script type="text/javascript">

    /**
     * 自定义验证规则
     */
    function validateForm() {
        $("#form_addOrEdit").bootstrapValidator({
            message: "无效的值",
            feedbackIcons: {
                valid: "glyphicon glyphicon-ok",
                invalid: "glyphicon glyphicon-remove",
                validating: "glyphicon glyphicon-refresh"
            },
            fields: {
                imageInfo_1: {
                    validators: {
                        notEmpty: {message: "请上传图片"},
                        file: {maxSize: 1024 * 1024, message: '请上传一张最大不超过1M的jpg/png/gif图片文件'}
                    }
                },
                trueName: {
                    validators: {
                        notEmpty: {message: "真实姓名不可为空"},
                        stringLength: {max: 20, message: "真实姓名最大长度为20"},
                        regexp: {
                            regexp: validateUtil.chinese,
                            message: '真实姓名为汉字'
                        }
                    }
                },
                nikeName: {
                    validators: {
                        notEmpty: {message: "昵称不可为空"},
                        stringLength: {max: 50, message: "昵称最大长度为50"}
                    }
                },
                qq: {
                    validators: {
                        notEmpty: {message: "QQ号码不可为空"},
                        stringLength: {max: 15, message: "QQ号码最大长度为15"},
                        regexp: {
                            regexp: validateUtil.qq,
                            message: 'qq号码格式错误'
                        }
                    }
                },
                mobile: {
                    validators: {
                        notEmpty: {message: "手机号不可为空"},
                        regexp: {
                            regexp: validateUtil.phone,
                            message: '手机号码格式错误'
                        }
                    }
                },
                phone: {
                    validators: {
                        notEmpty: {message: "电话号码不可为空"},
                        regexp: {
                            regexp: validateUtil.tel,
                            message: '联系电话格式错误'
                        }
                    }
                }
            }
        });
    }

    /**
     * 编辑店铺客服信息
     */
    <shiro:hasPermission name="back_gotoCustomerServicePage_update">
    function editInfo() {
        $("#myModalLabel2").empty().text("修改店铺客服信息");
        /**获取选中行的id**/
        var selectedRow = $("#tt").bootstrapTable('getSelections');
        if (selectedRow.length == 1) {
            var id = selectedRow[0].customerServiceId;
            $("#btn_edit").attr("data-target", "#myModal2");/**选中了记录后才可打开对应的模态框**/
            $.ajax({
                type: "POST",
                dataType: "JSON",
                url: "${basePath}/back/customerService/getCustomerServiceInfo.sjson",
                data: {customerServiceId: id},
                success: function (result) {
                    var data = JSON.parse(result.data);
                    /**隐藏域**/
                    $("#shopInfoId").val(data[0].shopInfoId);
                    $("#customerServiceId").val(data[0].customerServiceId);
                    $("#workNumber").val(data[0].workNumber);
                    $("#imageUrl_1").val(data[0].photoUrl);
                    /**可见表单控件**/
                    $("#trueName").val(data[0].trueName);
                    $("#nikeName").val(data[0].nikeName);
                    $("#mobile").val(data[0].mobile);
                    $("#phone").val(data[0].phone);
                    $("#qq").val(data[0].qq);
                    $("#useState_" + data[0].useState).attr("checked", "checked");

                    /**回写预览上传文件所需的信息，如果有上传图片功能添加此代码，否则可以去掉**/
                    initImageForUpdate(1,"sys_shop", "image_shopInfo", 1, 36, 36, "${uploadPath}", data[0].photoUrl);
                    reValidateForm();
                    removeValidateField('imageInfo_1');
                }
            });
        } else {
            $("#btn_edit").attr("data-target", "");/**没有选中记录不可打开模态框**/
            showMsg("请选择一行记录！");
        }
    }
    </shiro:hasPermission>

    /**
     * 选择店铺
     */
    <shiro:hasPermission name="back_gotoCustomerServicePage_add">
    function addInfo(){
        $("#myModalLabel").empty().text("选择店铺");
        /** 重置当前未选中的列表中的查询条件**/
        $("#qform_sub")[0].reset();
    }
    </shiro:hasPermission>

    /**
     * 选择店铺
     */
    $(function(){
        var $tt_shopInfoList = $("#tt_shopInfoList").bootstrapTable({
            url: '${basePath}/back/customerService/listShopInfo.sjson?',         	/**请求后台的URL（*）**/
            method: 'post',                       	/**请求方式（*）**/
            contentType: "application/x-www-form-urlencoded",
            dataType: 'json',
            toolbar: '#toolbar2',               	    /**工具按钮用哪个容器**/
            striped: false,                      	/**是否显示行间隔色**/
            cache: false,                       	/**是否使用缓存，默认为true，所以一般情况下需要设置一下这个属性（*）**/
            pagination: true,                   	/**是否显示分页（*）**/
            sortable: false,                    	/**是否启用排序**/
            sortOrder: 'asc',                   	/**排序方式**/
            queryParamsType: '',
            sidePagination: 'server',           	/**分页方式：client客户端分页，server服务端分页（*）**/
            pageNumber: 1,
            pageSize:10,							/**初始化加载第一页，默认第一页**/
            pageList: [5,10, 25, 50],        	    /**可供选择的每页的行数（*）**/
            search: false,                       	/**是否显示表格搜索，此搜索是客户端搜索，不会进服务端，所以，个人感觉意义不大**/
            strictSearch: true,
            showColumns: true,                  	/**是否显示所有的列**/
            showRefresh: true,                  	/**是否显示刷新按钮**/
            minimumCountColumns: 2,             	/**最少允许的列数**/
            clickToSelect: true,                	/**是否启用点击选中行**/
            uniqueId: 'shopInfoId',                  /**每一行的唯一标识，一般为主键列**/
            singleSelect  : true,                   /** 单选checkbox**/
            showToggle:false,                    	/**是否显示详细视图和列表视图的切换按钮**/
            cardView: false,                    	/**是否显示详细视图**/
            detailView: false,                  	/**是否显示父子表**/
            columns: [
                {checkbox: true},
                {field: 'Number', title: '编号', align: 'center', valign: 'middle', width: '50px',
                    formatter: function (value, row, index) {
                        var page = $tt_shopInfoList.bootstrapTable("getPage");
                        return page.pageSize * (page.pageNumber - 1) + index + 1;
                    }
                },
                {field: 'shopName', title: '店铺名称', align: 'center', valign: 'middle'},
                {field: 'address', title: '详细地址(街道)', align: 'center', valign: 'middle'},
                {field: 'postCode', title: '邮政编码', align: 'center', valign: 'middle'},
                {field: 'mainProduct', title: '主要销售产品', align: 'center', valign: 'middle'},
                {field: 'email', title: '电子邮箱', align: 'center', valign: 'middle'},
                {field: 'phone', title: '联系电话', align: 'center', valign: 'middle'}
            ],
            queryParams: function (params) {
                /**特别说明，返回的参数的值为空，则当前参数不会发送到服务器端,这种指定请求参数的方式和datatables控价类似**/
                params.shopName = $("#q_sub_shopName").val();
                params.currentPage = params.pageNumber;
                return params;
            }
        });

        /**表单查询**/
        $("#btn_query_sub").click(function () {
            $("#tt_shopInfoList").bootstrapTable('refresh');
        });
    });

    /**添加店铺客服信息**/
    function saveShopInfoList(){
        $("#myModalLabel2").empty().text("添加店铺客服信息");
        /**获取选中行的id**/
        var selectedRow= $("#tt_shopInfoList").bootstrapTable('getSelections');
        if (selectedRow.length == 1) {
            var id = selectedRow[0].shopInfoId;
            /** 获取值放入隐藏域 **/
            $("#shopInfoId").val(id);
            repeatSave();
            /** 重置添加表单 **/
            $("#form_addOrEdit")[0].reset();
        } else {
            $("#btn_addCustomerService").attr("data-target", "");/**没有选中记录不可打开模态框**/
            showMsg("请选择一行记录！");
        }
    }

    /**多次添加客服信息**/
    function repeatSave() {
        $("#btn_addCustomerService").attr("data-target", "#myModal2");/**选中了记录后才可打开对应的模态框**/
        /**清空隐藏域的值**/
        $("#customerServiceId").val("");
        $("#imageUrl_1").val("");
        /**如果有上传图片功能添加此代码，否则可以去掉**/
        initImageForAdd(1,"sys_shop", "image_shopInfo", 1, 36, 36);
    }

    /**
     * 表单提交及验证初始化
     */
    $(document).ready(function() {
        if($("#form_addOrEdit").length>0){ /**判断当前页面是否有填写表单并检验**/
            validateForm();
            /**Modal验证销毁重构**/
            $('#myModal2').on('hidden.bs.modal', function() {
                reValidateForm();
            });
        }
    });

    /**
     * 重置表单验证
     */
    function reValidateForm(){
        $("#form_addOrEdit").data('bootstrapValidator', null);
        validateForm();
    }

    /**
     * 指定字段移除验证
     */
    function removeValidateField(validateField){
        $("#form_addOrEdit").bootstrapValidator('enableFieldValidators', validateField, false);
    }

    /**
     * 指定表单字段进行重新验证
     */
    function rebuildValidateField(validateField){
        $("#form_addOrEdit").bootstrapValidator('enableFieldValidators', validateField, true);
    }

    /** 表单异步提交**/
    /** fileUploadStateValue 1:没有选中文件上传或没有上传文件功能 2：选中未上传 3：选中文件上传成功**/
    var isValid;
    function saveShopCustomerService() {
        /** 开启验证**/
        $("#form_addOrEdit").data('bootstrapValidator').validate();
        isValid=$("#form_addOrEdit").data('bootstrapValidator').isValid();
        if(isValid){  /** 验证通过后提交表单**/
            var options = {
                url: $("#form_addOrEdit").attr("action"),
                type : "post",
                dataType:"json",
                success : function(data) {
                    if(data.success==true){
                        /** 先重置查询框的值**/
                        resetQueryForm();
                        /** 重新刷新列表数据**/
                        $("#tt").bootstrapTable('refresh');
                        if (data.msg=="true"){
                            showMsg("保存成功！");
                            /** 重置添加表单 **/
                            $("#form_addOrEdit")[0].reset();
                            repeatSave();
                        }else{
                            /** 自动关闭弹出模态框窗口**/
                            $(".close").click();
                            showMsg("保存成功！");
                        }
                    }else{
                        showMsg("保存失败！");
                    }
                }
            };
            $("#form_addOrEdit").ajaxSubmit(options);
        }else{ /** 验证失败了直接返回 **/

        }
    }

</script>
<!--编辑模态框（Modal） -->
<div class="modal fade" id="addOrEditModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true" data-backdrop="static">
    <div class="modal-dialog" style="width:90%">
        <div class="modal-content">
            <div class="modal-header">
                <button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
                <h5 class="modal-title" id="myModalLabel"></h5>
            </div>

            <div class="modal-body" style="padding-top: 5px;">
                <!-- 查询条件 -->
                <div class="panel panel-default" style="margin-top: 15px;">
                    <div class="panel-body">
                        <form id="qform_sub" class="form-horizontal">
                            <div class="form-group" style="margin-top:15px">
                                <div class="col-sm-2" style="width:250px;">
                                    <div class="input-group input-group-sm">
                                        <span class="input-group-addon">店铺名称</span>
                                        <input type="text" class="form-control" id="q_sub_shopName" name="shopName" placeholder="请输入店铺名称"/>
                                    </div>
                                </div>
                                <div class="col-sm-2" style="width:160px;">
                                    <button type="button" id="btn_query_sub" class="btn btn-primary">查询</button>&nbsp;&nbsp;
                                    <button type="reset" class="btn btn-success" id="resetBtn" >重置</button>
                                </div>
                            </div>
                        </form>
                    </div>
                </div>
                <!-- 工具栏 -->
                <div id="toolbar2" class="btn-group">
                    <button id="btn_addCustomerService" type="button" class="btn btn-default" data-toggle="modal" data-target="#myModal2" onclick="saveShopInfoList()">
                        <span class="glyphicon glyphicon-plus" aria-hidden="true"></span>添加客服
                    </button>
                </div>
                <form id="form_select"  method="post" action="">
                    <!-- 渲染的table -->
                    <table id="tt_shopInfoList"></table>
                </form>
            </div>

            <div class="modal-footer">
                <button type="button" class="btn btn-default" data-dismiss="modal">关闭</button>
            </div>
        </div><!-- /.modal-content -->
    </div><!-- /.modal -->
</div>
<div class="modal fade" id="myModal2" tabindex="-1" role="dialog" aria-labelledby="myModalLabel2" aria-hidden="true" data-backdrop="static">
    <div class="modal-dialog" style="width:70%">
        <div class="modal-content">
            <div class="modal-header">
                <button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
                <h5 class="modal-title" id="myModalLabel2"></h5>
            </div>

            <div class="modal-body">
                <form id="form_addOrEdit" method="post" action="${basePath}/back/customerService/saveOrUpdateCustomerService.sjson">
                    <input id="shopInfoId" type="hidden" name="shopInfoId" value="${shopInfoId}"/>
                    <input id="customerServiceId" type="hidden" name="customerServiceId" noclear="true"/>
                    <input id="workNumber" type="hidden" name="workNumber" value=""/>
                    <table align="center" class="addOrEditTable table-bordered table" style="width:100%;">
                        <tr>
                            <td class="toright_td" width="150px"><span style="color:red">* </span>客服头像:&nbsp;&nbsp;</td>
                            <td class="toleft_td">
                                <div class="container">
                                    <input id="imageUrl_1" type="hidden" name="photoUrl" value=""/>
                                    <div class="form-group" id="fileWrap1"></div>
                                </div>
                                <span style="color:red">提示：请上传规格宽36px，高36px的图片</span>
                            </td>
                        </tr>
                        <tr>
                            <td class="toright_td" width="150px"><span style="color:red">* </span>真实姓名:&nbsp;&nbsp;</td>
                            <td class="toleft_td">
                                <div class="form-group">
                                    <input type="text" class="form-control input-sm" id="trueName" name="trueName" placeholder="请输入真实姓名"/>
                                </div>
                            </td>
                        </tr>
                        <tr>
                            <td class="toright_td" width="150px"><span style="color:red">* </span>昵称:&nbsp;&nbsp;</td>
                            <td class="toleft_td">
                                <div class="form-group">
                                    <input type="text" class="form-control input-sm" id="nikeName" name="nikeName" placeholder="请输入昵称"/>
                                </div>
                            </td>
                        </tr>
                        <tr>
                            <td class="toright_td" width="150px"><span style="color:red">* </span>QQ号码:&nbsp;&nbsp;</td>
                            <td class="toleft_td">
                                <div class="form-group">
                                    <input type="text" class="form-control input-sm" id="qq" name="qq" placeholder="请输入QQ号码"/>
                                </div>
                            </td>
                        </tr>
                        <tr>
                            <td class="toright_td" width="150px"><span style="color:red">* </span>手机号:&nbsp;&nbsp;</td>
                            <td class="toleft_td">
                                <div class="form-group">
                                    <input type="text" class="form-control input-sm" id="mobile" name="mobile" placeholder="请输入手机号"/>
                                </div>
                            </td>
                        </tr>
                        <tr>
                            <td class="toright_td" width="150px"><span style="color:red">* </span>电话号码:&nbsp;&nbsp;</td>
                            <td class="toleft_td">
                                <div class="form-group">
                                    <input type="text" class="form-control input-sm" id="phone" name="phone" placeholder="请输入电话号码"/>
                                </div>
                            </td>
                        </tr>
                        <tr>
                            <td class="toright_td" width="150px"><span style="color:red">* </span>是否废弃:&nbsp;&nbsp;</td>
                            <td class="toleft_td">
                                <label class="checkbox-inline">
                                    <input type="radio" name="useState" id="useState_1" class="radioInput" value="1" checked="checked">&nbsp;正常使用
                                </label>
                                <label class="checkbox-inline">
                                    <input type="radio" name="useState" id="useState_0" class="radioInput" value="0">&nbsp;废弃
                                </label>
                            </td>
                        </tr>
                    </table>
                </form>
            </div>

            <div class="modal-footer">
                <button type="button" id="validateBtn2" class="btn btn-primary"  onclick="saveShopCustomerService()">保存</button>
                <button type="button" class="btn btn-default" data-dismiss="modal">取消</button>
            </div>
        </div><!-- /.modal-content -->
    </div><!-- /.modal -->
</div>
